using System;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using IsolationLevel=System.Transactions.IsolationLevel;

namespace Budgeteer.Services.DataProviders
{
    public abstract class BaseDataProvider
    {
        private static readonly int commandTimeout = 100;
        private readonly string connectionString; 
            //"server=(local);database=Budgeteer;Trusted_Connection=true;Min Pool Size=1;Max Pool Size=10"

        public BaseDataProvider(string connectionString)
        {
            this.connectionString = connectionString;
        }

        public static TransactionScope CreateTransactionScope()
        {
            return CreateTransactionScope(IsolationLevel.RepeatableRead);
        }

        public static TransactionScope CreateTransactionScope(IsolationLevel isolationLevel)
        {
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = isolationLevel;
            return new TransactionScope(TransactionScopeOption.Required,options);
        }

        protected static SqlCommand CreateCommand(string commandText,
                                                  SqlConnection connection)
        {
            SqlCommand command = connection.CreateCommand();

            command.CommandType = CommandType.Text;
            command.CommandText = commandText;
            command.CommandTimeout = commandTimeout;

            return command;
        }

        protected SqlConnection CreateConnection()
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connectionString);

                conn.Open();

                return conn;
            }
            catch(Exception)
            {
                if(conn != null)
                    conn.Dispose();

                throw;
            }
        }

        protected static void SetParameter(SqlCommand command,
                                           string name,
                                           object value)
        {
            SetParameter(command,name,value,DBNull.Value);
        }

        protected static void SetParameter(SqlCommand command,
                                           string name,
                                           object value,
                                           object valueIfNull)
        {
            SqlParameter p = new SqlParameter();

            p.ParameterName = name;
            p.Value = value ?? valueIfNull;

            command.Parameters.Add(p);
        }
    }
}